/**
 * 防抖处理函数 适用于点击事件
 * @param {function}  func        回调
 * @param {number}    wait      时间窗口的间隔
 * @param {boolean}    immediate     是否立即执行
 */

export function debounce(func, wait = 500, immediate = true) {
  let timer, ctx, args
  const later = () => setTimeout(() => {
    timer = null
    if (!immediate) {
      func.call(ctx, ...args)
      ctx = args = null
    }
  }, wait)

  return function() {
    if (!timer) {
      timer = later()
      if (immediate) {
        func.call(this, ...arguments)
      } else {
        ctx = this
        args = arguments
      }
    } else {
      clearTimeout(timer)
      timer = later()
    }
  }
}

/**
 * 节流处理  适用于懒加载等场景
 * @param {function}  func      回调
 * @param {number}    wait      时间窗口的间隔
 */

export function throttle(func, wait = 1000) {
  let timer; let run = true
  const later = () => setTimeout(() => {
    func.call(this, ...arguments)
    run = true
  }, wait)

  return function() {
    if (!run) return
    run = false
    clearTimeout(timer)
    timer = later()
  }
}
